<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    /* 两个具有部分相同样式的元素 */
    /* .box1{width:100px;height: 100px;background: red;position: absolute;left:0;top:0;}
    .box2{width:100px;height: 100px;background: green;position: absolute;left:0;top:120px;} */

    /* 先定义一个完整样式，另一个全部继承，然后再改写 */
    /* .box1, .box2{width:100px;height: 100px;background: red;position: absolute;left:0;top:0;}
    .box2{background: green; top:120px;} */

    /* 将两个元素的公共样式，抽象成公共对象 */
    /* 两个对象都继承公共样式后，再改写自身 */
    /* .box1, .box2{width:100px;height: 100px;position: absolute;left:0;}
    .box1{background: red;top:0;}
    .box2{background: green;top:120px;} */
  </style>
</head>
<body>
  <div class="box1"></div>
  <div class="box2"></div>
</body>
<script>

  function Drag(ele){
    this.ele = ele;
    this.m = this.move.bind(this);
    this.u = this.up.bind(this);
    
    this.addEvent();
  }
  Drag.prototype.addEvent = function(){
    this.ele.addEventListener( "mousedown", this.down.bind(this) );
  }
  Drag.prototype.down = function(eve){
    this.downE = eve || window.event;
    
    document.addEventListener("mousemove", this.m );
    document.addEventListener("mouseup", this.u );
  }
  Drag.prototype.move = function(eve){
    this.moveE = eve || window.event;
    this.ele.style.left = this.moveE.pageX - this.downE.offsetX + "px";
    this.ele.style.top = this.moveE.pageY - this.downE.offsetY + "px";
  }
  Drag.prototype.up = function(){
    document.removeEventListener("mousemove", this.m );
    document.removeEventListener("mouseup", this.u );
  }


  function SmallDrag(ele){
    Drag.call(this, ele);
  }
  SmallDrag.prototype = {
    ...Drag.prototype,
    move(eve){
      this.moveE = eve || window.event;

      let l = this.moveE.pageX - this.downE.offsetX;
      let t = this.moveE.pageY - this.downE.offsetY;

      if(l<0) l=0;
      if(t<0) t=0; 

      this.ele.style.left = l + "px";
      this.ele.style.top = t + "px";
    }
  }


  const box1 = document.querySelector('.box1');
  const box2 = document.querySelector('.box2');
  
  // 需求1：多个元素都需要拖拽
  // 不需要继承
  // new Drag(box1);
  // new Drag(box2);

  // 需求2：多个元素都需要拖拽，但有的有边界限定，有的没有边界限定
  // 需要继承
  // 没有边界限定
  new Drag(box1);
  new SmallDrag(box2);

</script>
</html>